package com.team7.system.service.impl;

import com.team7.common.entity.Permission;
import com.team7.common.entity.RolePermission;
import com.team7.common.entity.User;
import com.team7.common.vo.CommonResult;
import com.team7.common.vo.PermissionVo;
import com.team7.common.vo.RolePermissionVo;
import com.team7.system.dao.PermissionDao;
import com.team7.system.dao.RolePermissionDao;
import com.team7.system.service.PermissionService;
import com.team7.common.utils.WebUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * @program: team7-Object
 * @description:
 * @author: 杨海涛
 * @create: 2021-10-19 09:06
 **/
@Service
public class PermissionServiceImpl implements PermissionService {
    @Resource
    private PermissionDao permissionDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource
    private RolePermissionDao rolePermissionDao;


    //递归来获取子权限的权限id
    public List<Permission>  getChildPermission(List<Permission> permissions,String pid){
        List<Permission> childs=new ArrayList<>();

        for (Permission permission:permissions){
            if (permission.getPid().equals(pid)){
                childs.add(permission);
            }
        }
        for (Permission child:childs){
            child.setChildren(getChildPermission(permissions,child.getId()));
        }
        return childs;
    }
    //自定义方法：获取权限的子权限
    private List<Permission> getChildren(Permission chPermission,List<Permission> permissions){
        //1.创建集合，存放子权限
        List<Permission> childrenPermissions = new ArrayList<>();
        //2.遍历判断当前权限是否有子权限，如果有则添加到子权限集合中
        permissions.forEach(permission -> {
            if (chPermission.getId().equals(permission.getPid()))
                childrenPermissions.add(permission);
        });
        //3.将子权限集合放入当前权限的子权限中
        chPermission.setChildren(childrenPermissions);
        if (childrenPermissions.size()==0){
            return childrenPermissions;
        }
        //4.为子权限设置子权限
        childrenPermissions.forEach(childrenPermission -> {
            childrenPermission.setChildren(getChildren(childrenPermission,permissions));
        });
        return childrenPermissions;
    }


    @Override
    public CommonResult getAllPermission(){//获取所有权限
        //获取请求头的token值  TODO
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");

        //将String转为需要的对象类型
        String s = redisTemplate.opsForValue().get(token);
        User user = JSON.parseObject(s, User.class);
        List<Permission> permissions = permissionDao.getAllPermission(user.getId());
        //创建一个一级权限数组
        List<Permission> childPermission = new ArrayList<>();
        //查找并遍历所有的一级菜单放入childPermission
        for (Permission permission:permissions
        ) {//权限表id为1是权限的所有数据
            if (permission.getPid().equals("1")){
                childPermission.add(permission);
            }
        }
        for (Permission first:childPermission
        ) {
            first.setChildren(getChildPermission(permissions, first.getId()));
        }
        return new CommonResult(2000,"查询成功",childPermission);
    }
    @Override
    public CommonResult findAllPermissionById() {
        // TODO
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        String s = redisTemplate.opsForValue().get(token);
        User user = JSON.parseObject(s, User.class);
        //查询出所有权限
        List<Permission> permissions= permissionDao.findAllPermissionById(user.getId());
        List<Permission> childPermission = new ArrayList<>();
        //遍历出所有的一级权限
        for (Permission permission:permissions){
            if (permission.getPid().equals("1")){
                childPermission.add(permission);
            }
        }
        //为一级权限的添加二级权限
        for (Permission first : childPermission) {
            first.setChildren(getChildPermission(permissions,first.getId()));
        }
        return new CommonResult(2000,"查询成功",childPermission);
        //return null;
    }

    @Override
    public CommonResult findPermissionByRoleId(String roleId) {
        //拿到所有权限
        List<Permission> permissions=permissionDao.selectList(null);

        List<Permission> firtPermission=new ArrayList<>();

        //将一级菜单放入firtPermission
        for(Permission p:permissions){
            if(p.getPid().equals("1")){
                firtPermission.add(p);
            }
        }

        //为一级菜单赋值children属性
        for(Permission first:firtPermission){
            first.setChildren(getChildPermission(permissions,first.getId()));
        }

        //通过roleId查询该角色具有的权限
        QueryWrapper<RolePermission> wrapper=new QueryWrapper<>();
        wrapper.eq("role_id",roleId);
        List<RolePermission> rolePermissionList=rolePermissionDao.selectList(wrapper);

        List<String> rolePermissionIds=rolePermissionList.stream().map(item->item.getPermissionId()).collect(Collectors.toList());

        //返回allPermissions所有的权限----》checkItems用户具有的权限id
        Map<String,Object> map=new HashMap<>();
        map.put("allPermissions",firtPermission);
        map.put("checkItems",rolePermissionIds);
        return new CommonResult(2000,"查询成功",map);
        //return null;
    }

    @Override
    @Transactional
    public CommonResult confirmFenPermission(RolePermissionVo rolePermissionVo) {
        //先将角色权限表中的role_id对应的权限删除
        QueryWrapper<RolePermission> wrapper=new QueryWrapper<>();
        wrapper.eq("role_id",rolePermissionVo.getRoleId());
        rolePermissionDao.delete(wrapper);

        //再插入对应角色的权限
        for(String permissionId:rolePermissionVo.getPermissionIds()){
            RolePermission permission=new RolePermission();
            permission.setGmtCreate(LocalDateTime.now().toString());
            permission.setGmtModified(LocalDateTime.now().toString());
            permission.setIsDeleted(0);
            permission.setRoleId(rolePermissionVo.getRoleId());
            permission.setPermissionId(permissionId);
            rolePermissionDao.insert(permission);
        }
        return new CommonResult(2000,"成功",null);
        //return null;
    }

    @Override
    public CommonResult findAllByPage(Integer page, Integer limit, PermissionVo permissionVo) {
        Page<Permission> page1 = new Page(page, limit);
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("is_deleted",0);
        List<Permission> permissions = permissionDao.selectList(wrapper);
        //为权限设置身份备注
        permissions.forEach(permission -> {
            if (permission.getType()==1 && permission.getPid().equals("1"))
                permission.setTypeName("主目录");
            else if (permission.getType()==1)
                permission.setTypeName("菜单");
            else
                permission.setTypeName("按钮");
        });

        if (StringUtils.isNotEmpty(permissionVo.getName())){
            //根据permissionVo的name进行判断，不为空则为搜索
            wrapper.like("name",permissionVo.getName());
            wrapper.eq("type",1);
            wrapper.ne("pid",1);
            Page<Permission> permissionPage = permissionDao.selectPage(page1,wrapper);

            permissionPage.getRecords().forEach(permission -> {
                if (permission.getType()==1 && permission.getPid().equals("1"))
                    permission.setTypeName("主目录");
                else if (permission.getType()==1)
                    permission.setTypeName("菜单");
                else
                    permission.setTypeName("按钮");
                //递归设置子菜单
                permission.setChildren(getChildren(permission,permissions));
            });

            return new CommonResult(2000,"成功",permissionPage);
        }else {
            //获取所有的pid为1的菜单，，即获取所有的目录
            wrapper.eq("pid",1);
            Page<Permission> permissionPage = permissionDao.selectPage(page1, wrapper);
            permissionPage.getRecords().forEach(permission -> {
                permission.setTypeName("主目录");
                //为目录添加子菜单
                permission.setChildren(getChildren(permission,permissions));
            });
            return new CommonResult(2000,"成功",permissionPage);
        }

        //return null;
    }

    @Override//-----------------
    @Transactional
    public CommonResult deleteById(PermissionVo permissionVo) {
        for (String permissionId : permissionVo.getPermissionIds()) {
            int i1 = permissionDao.deleteById(permissionId);
            QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
            wrapper.eq("permission_id",permissionId);
            rolePermissionDao.delete(wrapper);
        }
        return new CommonResult(2000,"删除成功了",null);
        //return null;
    }

    @Override
    @Transactional
    public CommonResult insert(Permission permission) {
        int i = permissionDao.insert(permission);
        return new CommonResult(2000,"新增成功了",permission);
        //return null;
    }

    @Override
    public CommonResult findById(String id) {
        Permission permission = permissionDao.selectById(id);
        return new CommonResult(2000,"查找成功",permission);
        //return null;
    }

    @Override
    @Transactional
    public CommonResult update(Permission permission) {
        permissionDao.updateById(permission);
        return new CommonResult(2000,"修改成功",permission);
        //return null;
    }
}
